package com.im.test.main;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.im.test.bean.LiveRoomMessageBean;
import com.im.test.constant.WebSocketBaseRequestType;
import com.im.test.constant.WebSocketRequestType;
import com.im.test.core.MyWebSocketClinet;
import com.im.test.core.WebSocketMap;
import com.im.test.core.WebSocketMessageListener;
import com.out.sourcing.dto.ResponseResult;
import com.out.sourcing.request.viewer.EnterRoomJudgeRequest;
import com.out.sourcing.response.viewer.ViewerInfoResponse;
import com.out.sourcing.util.AESEncryptUtils;

import java.net.SocketException;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class WebSocketSart {

    /**
     * 创建websocket链接
     * @param count
     * @param time
     * @param roomCode
     * @param mode 0保持连接 1发送消息
     */
    public void test(int count, long time, String roomCode, String mode){
        for (int i = 0; i < count; i++) {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Executors.newScheduledThreadPool(1).execute(()->{
                ViewerInfoResponse token = token(roomCode);
                MyWebSocketClinet myWebSocketClinet = create(token.getImUrl(), token.getImToken());
                openConnection(myWebSocketClinet);

                webEnterRoom(token,roomCode);
                while (true){
                    try {
                        joinRoom(myWebSocketClinet,token);
                        TimeUnit.MILLISECONDS.sleep(200);
                    }catch (Exception e){

                    }
                }
//                if("1".equals(mode))
//                send(myWebSocketClinet,time,token);
            });
        }

    }

    /**
     * 获取token
     * @return
     */
    public ViewerInfoResponse token(String roomCode){
        EnterRoomJudgeRequest request = new EnterRoomJudgeRequest();
        request.setFormat("flv");
        request.setRoomCode(roomCode);
        String zh = HttpRequest.post("http://192.168.2.148:9088/viewer/room/queryBackdrop")
                .header("Accept-Language", "zh")
                .body(JSONObject.toJSONString(request))
                .execute().body();
        return JSONObject.parseObject(AESEncryptUtils.decrypt(zh,AESEncryptUtils.AES_DATA_SECURITY_KEY)).getJSONArray("data").getJSONObject(0).toJavaObject(ViewerInfoResponse.class);
    }

    public MyWebSocketClinet create(String url,String token){
        URI uri = URI.create("ws://" + url + "/chatsocket?request=" + token);
        MyWebSocketClinet clinet = new MyWebSocketClinet(uri);
        WebSocketMessageListener webSocketMessageListener = new WebSocketMessageListener();
        clinet.setMessageListener(webSocketMessageListener);
        return clinet;
    }

    public void openConnection(MyWebSocketClinet clinet){
        while (!clinet.isOpen()){
            clinet.tryConnect(false);
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void webEnterRoom(ViewerInfoResponse viewerInfoResponse,String roomCode){
        EnterRoomJudgeRequest request = new EnterRoomJudgeRequest();
        request.setViewerId(viewerInfoResponse.getId());
        request.setRoomCode(roomCode);
        String zh = HttpRequest.post("http://192.168.2.148:9088/viewer/room/queryBackdrop")
                .header("Accept-Language", "zh")
                .body(JSONObject.toJSONString(request))
                .execute().body();
    }

    public void joinRoom(MyWebSocketClinet clinet,ViewerInfoResponse viewerInfoResponse){
        //加入房间
        LiveRoomMessageBean liveRoomMessageBean = new LiveRoomMessageBean();
        liveRoomMessageBean.setG(0);
        liveRoomMessageBean.setH(null);
        liveRoomMessageBean.setIrs(0);
        liveRoomMessageBean.setIa(0);
        liveRoomMessageBean.setIsa(0);
        liveRoomMessageBean.setV(5);
        liveRoomMessageBean.setL(100);
        liveRoomMessageBean.setN(viewerInfoResponse.getNickName());
//        liveRoomMessageBean.setM("进入房间");
        liveRoomMessageBean.setI(viewerInfoResponse.getId().toString());
        liveRoomMessageBean.setUt(3);
        clinet.sendMessage(WebSocketRequestType.RequestAction.ENTER.getValue(), JSONObject.toJSONString(liveRoomMessageBean),true);
    }
    public void send(MyWebSocketClinet clinet,long time,ViewerInfoResponse viewerInfoResponse){
        while (clinet.isOpen()){
            LiveRoomMessageBean liveRoomMessageBean1 = new LiveRoomMessageBean() {{
                setG(2);
                setIrs(0);
                setIa(0);
                setIsa(0);
                setV(5);
                setL(100);
                setN(viewerInfoResponse.getNickName());
                setM("用户"+viewerInfoResponse.getNickName()+",正在发送消息");
                setI(viewerInfoResponse.getId().toString());
                setUt(1);
            }};
            clinet.sendMessage(WebSocketRequestType.RequestAction.MESSAGE.getValue(), JSONObject.toJSONString(
                    liveRoomMessageBean1
            ),true);
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
